package controllers

import (
	"BeegoFirst/models"
	"BeegoFirst/torch"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"math"
	"path"
	"time"
)

type IndexController struct {
	beego.Controller
}

func (This *IndexController) Get() {

	pageSize := 2
	pageIndex := 1 //页码默认1
	index, err := This.GetInt("page")
	if err == nil {
		pageIndex = index
	}

	var articles []models.Article
	var count int64
	o := orm.NewOrm()
	qs := o.QueryTable("Article").RelatedSel("ArticleType")

	selects := This.GetString("select")

	if selects == "" {
		_, err = qs.Limit(pageSize, (pageIndex-1)*pageSize).All(&articles) // 一页多少， 起始位置
		if err != nil {
			beego.Info(err)
			This.Ctx.WriteString("查询失败")
		}

		count, _ = qs.Count()

	} else {
		_, err = qs.Filter("ArticleType__Title", selects).
			Limit(pageSize, (pageIndex-1)*pageSize).
			All(&articles)
		if err != nil {
			beego.Info(err)
			This.Ctx.WriteString("查询失败")
		}

		count, _ = qs.Filter("ArticleType__Title", selects).Count()

	}

	userName := This.GetSession("userName")

	pageCount := int(math.Ceil(float64(count) / float64(pageSize))) //向上取整并且转int

	//获取列表页
	var types []models.ArticleType
	o.QueryTable("ArticleType").All(&types)

	This.Layout = "layout.html" //大模板拼接

	//小模版绚烂
	This.LayoutSections = make(map[string]string)
	This.LayoutSections["IndexJs"] = "head_js.html"

	This.Data["types"] = types
	This.Data["select"] = selects
	This.Data["pageCount"] = pageCount
	This.Data["indexPage"] = pageIndex
	This.Data["count"] = count
	This.Data["articles"] = articles
	This.Data["userName"] = userName
	This.TplName = "index.html"
}

type AddController struct {
	beego.Controller
}

func (This *AddController) Get() {
	o := orm.NewOrm()

	var types []models.ArticleType
	o.QueryTable("ArticleType").All(&types)

	This.Data["types"] = types
	This.Layout = "layout.html"

	This.TplName = "add.html"
}

func (This *AddController) Post() {
	title := This.GetString("articleName")
	content := This.GetString("content")

	sle := This.GetString("select")
	if sle == "" {
		This.Ctx.WriteString("下拉框无数据")
		return
	}

	o := orm.NewOrm()

	articleType := models.ArticleType{Title: sle}
	err := o.Read(&articleType, "Title")
	if err != nil {
		beego.Info("查询type错误", err)
		return
	}

	if !torch.All(title, content) {
		This.Ctx.WriteString("数据不完整")
		return
	}

	f, h, err := This.GetFile("uploadname")
	if h == nil {
		o := orm.NewOrm()
		arta := models.Article{Title: title, Content: content, ArticleType: &articleType}

		_, err = o.Insert(&arta)
		if err != nil {
			This.Ctx.WriteString("插入数据失败")
			beego.Info(err)
			return
		}

		This.Redirect("/api/index", 302)
		return

	}
	defer f.Close()

	if err != nil && h != nil {
		This.Ctx.WriteString("文件上传失败")
		return
	}

	if !(h != nil && torch.EatPicture(h.Filename)) {
		This.Ctx.WriteString("文件名错误")
		return
	}

	filename := fmt.Sprintf("%d%s", time.Now().Unix(), path.Ext(h.Filename))

	err = This.SaveToFile("uploadname", path.Join("./static/img", filename))
	if err != nil {
		beego.Info(err)
		This.Ctx.WriteString("保存失败")
		return
	}

	arta := models.Article{Title: title, Content: content, Img: filename, ArticleType: &articleType}

	_, err = o.Insert(&arta)
	if err != nil {
		This.Ctx.WriteString("插入数据失败")
		return
	}

	This.Redirect("/api/index", 302)

}

type ContentController struct {
	beego.Controller
}

func (This *ContentController) Get() {

	id, err := This.GetInt("id")

	if err != nil {
		This.Redirect("/", 302)
	}

	are := models.Article{}

	o := orm.NewOrm()
	o.QueryTable("Article").RelatedSel().Filter("Id", id).One(&are)
	if err != nil {
		This.Ctx.WriteString("没有这个数据")
	}

	are.Count += 1

	_, _ = o.Update(&are)

	//多对多，首先拿到插入对象
	m2m := o.QueryM2M(&are, "User")
	userName := This.GetSession("userName")
	beego.Info(userName)

	user := models.User{Username: userName.(string)}
	o.Read(&user, "userName")

	_, err = m2m.Add(&user)
	if err != nil {
		beego.Info(err)
		return
	}

	//_, err = o.LoadRelated(&are, "User")
	//if err != nil {
	//	beego.Info("err", err)
	//}

	var users []models.User
	o.QueryTable("User").Filter("Article__Article__Id", id).Distinct().All(&users)

	This.Data["are"] = are
	This.Layout = "layout.html"
	This.Data["users"] = users

	This.TplName = "content.html"
}

type DelController struct {
	beego.Controller
}

func (This *DelController) Get() {

	id, err := This.GetInt("id")
	if err != nil {
		This.Redirect("/api/index", 302)
		return
	}

	o := orm.NewOrm()
	are := models.Article{Id: id}

	o.Delete(&are)

	This.Redirect("/api/index", 302)

}

type UpDateController struct {
	beego.Controller
}

func (This *UpDateController) Get() {
	id, err := This.GetInt("id")
	if err != nil {
		This.Redirect("/", 302)
		return
	}

	are := models.Article{Id: id}

	o := orm.NewOrm()
	err = o.Read(&are)
	if err != nil {
		This.Redirect("/", 302)
		return
	}

	This.Data["are"] = are
	This.Layout = "layout.html"

	This.TplName = "update.html"
}

func (This *UpDateController) Post() {

	o := orm.NewOrm()
	id, err := This.GetInt("id")
	if err != nil {
		This.Ctx.WriteString("没有ID")
		return
	}

	are := models.Article{Id: id}
	err = o.Read(&are)
	if err != nil {
		This.Ctx.WriteString("数据不存在")
	}

	name := This.GetString("articleName")
	content := This.GetString("content")
	if !torch.All(name, content) {
		This.Ctx.WriteString("存在必填字段")
	}

	f, h, err := This.GetFile("uploadname")
	if err != nil {
		//This.Ctx.WriteString("图片加载错误")
		are.Content = content
		are.Title = name
		_, err = o.Update(&are)
		if err != nil {
			This.Ctx.WriteString("修改失败")
			return
		}

		This.Redirect("/", 302)
		return

	}

	defer f.Close()

	if !torch.EatPicture(h.Filename) {
		This.Ctx.WriteString("图片格式错误")
		return
	}

	filename := fmt.Sprintf("%d%s", time.Now().Unix(), path.Ext(h.Filename))

	err = This.SaveToFile("uploadname", "./static/img/"+filename)
	if err != nil {
		This.Ctx.WriteString("保存失败")
		beego.Info(err)
		return
	}

	are.Content = content
	are.Title = name
	are.Img = filename

	_, err = o.Update(&are)
	if err != nil {
		This.Ctx.WriteString("修改失败")
		return
	}

	This.Redirect("/", 302)

}
